<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="修改申报要素"
    width="700px"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form :model="formValues" label-position="top" ref="formRef" class="mx-5 my-5">
      <el-form-item label="海关编码">
        <div class="flex">
          <el-input
            v-model="formValues.customs_goods_code"
            style="width: 300px"
            placeholder="请输入"
          />
          <el-button style="margin-right: 10px" type="primary" @click="handleQuery"
            >申报要素维护项查询</el-button
          >
          <el-button type="primary" @click="navToCode()">跳转查询海关编码</el-button>
        </div>
      </el-form-item>
      <el-form-item label="申报要素维护项">
        <div
          class="flex"
          v-for="(item, index) in formValues.declare_elements_list"
          :key="index"
        >
          <div class="w-[60px] h-[34px] border text-center">{{ index }}</div>
          <div class="flex w-[500px]">
            <el-input
              v-model="item.text"
              placeholder="请输入维护项"
              :disabled="item.disabled"
            ></el-input>
            <el-input v-model="item.value" placeholder="请输入"></el-input>
          </div>
          <div class="w-20 flex ml-2">
            <svg-icon
              class="w-4 mt-2 icon icon-color"
              @click="handleCreate(item)"
              icon-class="add03"
            />
            <svg-icon
              class="w-4 mt-2 icon mr-3 ml-3"
              @click="handleDelete(item, index)"
              icon-class="jian"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="申报要素">
        <el-input
          v-model="formValues.declare_elements"
          placeholder="保存后自动生成"
          type="textarea"
          clearable
          :autosize="{ minRows: 2, maxRows: 4 }"
          disabled
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-checkbox
          v-model="is_all"
          :true-label="1"
          :false-label="2"
          label="修改所有绑定供应商"
        />
      </el-form-item> -->

      <div class="text-[#999]">
        <p>注：</p>
        <!-- <p>
          1、以上内容默认只修改'默认供应商'的申报要素,只有勾选'修改所有绑定供应商'才会修改该SKU绑定的所有供应商的申报要素。
        </p> -->
        <p>1、修改退税供应商的'申报要素'、系统会自动生成变更单,审核通过后执行修改。</p>
        <p>2、若填写海关编码，也将一同修改；</p>
      </div>
    </el-form>
    <template #footer>
      <div class="footer-btn">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import { batchDeclareElement } from "../api.js";
import { getCustomsDetail } from "@/api/index.js";
import { filterDeleteFlag } from "@/utils/index.js";
import { change_order_category } from "@/utils/data.js";
import { changeOrderExist } from "@/api/index.js";

const data = reactive({
  visible: false,
  loading: false,
  dev_status: false,
  formValues: {
    declare_elements_list: [],
    customs_goods_code: "",
  },
  sku_ids: [],
  is_all: 2,
  spu_category: "",
  is_refund_tax_list: [],
});

const {
  visible,
  loading,
  dev_status,
  formValues,
  sku_ids,
  is_all,
  spu_category,
  is_refund_tax_list,
} = toRefs(data);

const formRef = ref();
const emit = defineEmits(["refresh"]);
const load = ref(false);

const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  sku_ids.value = data.ids;
  dev_status.value = data.dev_status;
  spu_category.value = data.spu_category;
  is_refund_tax_list.value = data.is_refund_tax;
  formValues.value.declare_elements_list = [
    {
      text: "",
    },
  ];
  visible.value = true;
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (!valid) return;
  const messageArray = [];
  formValues.value.declare_elements_list.forEach((item, index) => {
    if (!item.text && !item.value) {
      messageArray.push(`第${index}项，申报要素维护项类型或者内容不能为空`);
    }
  });

  if (messageArray && messageArray.length) {
    ElMessageBox({
      title: "提示",
      message: () => <div>{messageArray.map((d) => h("p", null, d))}</div>,
    });
    return;
  }

  const is_flag = formValues.value.declare_elements_list.some((i) => i.value);
  if (!is_flag) {
    return ElMessage.warning("申报要素维护项文字值至少维护一项");
  }
  let declare_elements = "";
  formValues.value.declare_elements_list.forEach((item, index) => {
    const value = item.value || "";
    declare_elements += value;
    if (index < formValues.value.declare_elements_list.length - 1) {
      declare_elements += "｜";
    }
    item.sort = index;
    return item;
  });

  formValues.value.declare_elements = declare_elements;

  const is_category = spu_category.value.some((i) => {
    return change_order_category.includes(i.spu_category[0]);
  });

  const is_refund_tax = is_refund_tax_list.value.some((i) => {
    return i == 2;
  });

  if (dev_status.value && is_category && is_refund_tax) {
    const is_confirm = await handleConfirm();
    if (!is_confirm) return;
  }
  loading.value = true;

  try {
    const res = await batchDeclareElement(
      Object.assign(
        {},
        { sku_ids: sku_ids.value, data: formValues.value, is_all: is_all.value }
      )
    );
    if (res.code === 200) {
      ElMessage.success("操作成功");
      close(true);
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

const close = async (refresh) => {
  formValues.value = {};
  is_all.value = 2;
  await nextTick();
  await formRef.value.resetFields();
  if (refresh) emit("refresh");
  visible.value = false;
};
defineExpose({ open });

// 新增
const handleCreate = (item) => {
  if (item.disabled) {
    return ElMessage.warning("查询后申报要素维护项不支持添加，删除");
  }
  if (formValues.value.declare_elements_list.length == 20) {
    return ElMessage.warning("最多只能添加20条数据");
  }
  formValues.value.declare_elements_list.push({
    text: "",
  });
};

// 删除
const handleDelete = (item, index) => {
  if (item.disabled) {
    return ElMessage.warning("查询后申报要素维护项不支持添加，删除");
  }
  if (filterDeleteFlag(formValues.value.declare_elements_list)) {
    ElMessage.error("至少保留一条");
    return;
  }
  formValues.value.declare_elements_list.splice(index, 1);
};

const handleQuery = async () => {
  try {
    const res = await getCustomsDetail({
      customs_goods_code: formValues.value.customs_goods_code,
    });
    if (res.data) {
      formValues.value.declare_elements_list = res.data.declare_elements_list.map((i) => {
        i.disabled = 1;
        return i;
      });
    } else {
      ElMessage.error("暂无信息");
    }
  } catch (e) {
    throw Error(e);
  }
};

// 跳转查询海关编号
const navToCode = (code) => {
  if (code) {
    window.open(`http://www.hsbianma.com/search?keywords=${code}`, "_blank");
  } else {
    window.open("http://www.hsbianma.com/Home/Message", "_blank");
  }
};

const handleConfirm = () => {
  return new Promise(async (resolve, reject) => {
    changeOrderExist({
      sku_id: sku_ids.value,
    }).then(async (res) => {
      if (res.data.exist) {
        ElMessageBox.confirm(
          "所选数据中,在<商品资料变更单>存在待审核的变更单,无法修改，请审核通过后再进行调整；点击保存后，将自动剔除该类数据。",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      } else {
        ElMessageBox.confirm(
          "SKU开发状态=通过，且绑定的供应商存在是否退税=退税；更换默认供应商，或者修改退税供应商的‘报关中文名’、‘报关单位’、‘规格型号’、‘海关编码’、‘退税率’、‘申报要素’，点击确认后，系统将自动生成变更单，审核通过后执行修改，是否确认修改？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            resolve(true);
          })
          .catch(() => {
            reject(false);
          });
      }
    });
  });
};
</script>
<style lang="scss" scoped>
.footer-btn {
  :deep(.el-button + .el-button) {
    margin-left: 8px !important;
  }
}
</style>
